<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+status">
        <!--        <CommentDropdown v-model="postForm.comment_disabled"/>-->
        <!--        <PlatformDropdown v-model="postForm.platforms"/>-->
        <!--        <SourceUrlDropdown v-model="postForm.source_uri"/>-->
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <!--        <el-button v-loading="loading" type="warning" @click="draftForm" v-if="!this.isEdit">-->
        <!--          草稿箱-->
        <!--        </el-button>-->
      </sticky>

      <div class="createPost-main-container">
        <el-divider>01-動格传媒</el-divider>
        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400"/>
        </el-form-item>

          <el-card>
          <el-upload
            ref="upload"
            :headers="headers"
            action="/api/upload/audio"
            :before-upload="onBeforeUpload"
            :on-success="uploadSuccess"
            :on-remove="handleRemoveVideo"
            :on-progress="handProgress"
            :file-list="videoList"
            :show-file-list="false"
            :auto-upload="true"
            :accept="'.mp4,.avi,.mov'"
          >
            <el-button slot="trigger" size="small" type="primary" plain>上传视频</el-button>
            <!--            <el-button size="small" type="danger" @click="clearUpload" style="margin-left:10px">移除</el-button>-->
          </el-upload>
          <video
            style="margin-top:10px"
            v-if="postForm.video"
            ref="videoBox"
            id="testVideo"
            class="video-js"
            height="300px"
            preload="auto"
            controls=""
            :src="postForm.video"
          >
          </video>
          <el-progress :text-inside="true" :stroke-width="16" :percentage="uploadProgress" v-show="uploadProgress"
          ></el-progress>
          </el-card>
        <el-divider>01-動格摄制组设备<font style="color: #ccc">(点击图片上的编辑按钮即为编辑图片名称)</font></el-divider>
        <el-card>
          <el-upload
            action="/api/upload/image"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleSuccess"
            :auto-upload="true"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <el-image
                :src="file.url"
                fit="contain"
                style="height:146px;max-width:334px"
              >
              </el-image>
              <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file,fileList)"
        >
          <i class="el-icon-delete"></i>
        </span>

         <span
           class="el-upload-list__item-edit"
           @click="handlePictureEdit(file)"
           >
           <i class="el-icon-edit"></i>
        </span>
      </span>
            </div>
          </el-upload>
        </el-card>
      </div>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" :src="dialogImageUrl" alt="" fit="contain"></el-image>
    </el-dialog>
    <el-dialog :visible.sync="dialogEdit">
     <el-input v-model="fileName" placeholder="请输入图片名称"></el-input>
      <center>
      <el-button @click="changeFile" type="primary" style="margin-top:20px">
        保存
      </el-button>
      </center>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { searchUser } from '@/api/remote-search'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'
import { createBrand, fetchBrand } from '@/api/brand'

const defaultForm = {
  video: '', // 内容
  content: '', // 摘要
  images: '', // 图片
  id: undefined
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      //上传视频
      preventSumit: false,
      progressFactor: 0.96,
      uploadProgress: 0,
      headers: {},
      videoList: [],
      //结束
      disabled: false,
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        image: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        // display_time: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      status: 'draft',
      tempRoute: {},
      dialogEdit:false,
      fileName:'',
      fileKey:''
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.desc.length
    },
    // displayTime: {
    //   // set and get is useful when the data
    //   // returned by the back end api is different from the front end
    //   // back end return => "2013-06-25 06:59:25"
    //   // front end need timestamp => 1372114765000
    //   get() {
    //     return (+new Date(this.postForm.display_time))
    //   },
    //   set(val) {
    //     this.postForm.display_time = new Date(val)
    //   }
    // }
  },
  created() {
      this.fetchData()
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)

  },
  methods: {
    //上传视频
    onBeforeUpload(file) {
      this.progressFactor = Math.random(1)
      this.preventSumit = true
    },
    uploadSuccess(response, file, fileList) {
      // let { code , data:{picUrlList}, message } = response;
      if (response.code == 200) {
        this.videoList = [{ name: response.name, url: response.url }]
        this.uploadProgress = 100
        this.preventSumit = false
        this.postForm.video = this.videoList[0].url
        setTimeout(() => {
          this.uploadProgress = 0
        }, 1000)
      } else {
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
        this.preventSumit = false
      }
    },
    handleRemoveVideo(file) {
      this.$refs.upload.clearFiles()
      this.videoList = []
      this.postForm.video = ''
    },
    handProgress(file) {
      this.uploadProgress = parseInt(file.percent * this.progressFactor)
    },
    clearUpload() {
      if (!this.videoList.length) return false
      this.$refs.upload.clearFiles()
      this.videoList = []
      this.postForm.video = ''
    },
    //上传图片
    handleRemove(file, fileList) {
      const key = this.fileList.indexOf(file)
      this.fileList.splice(key, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePictureEdit(file){
       this.fileKey = this.fileList.indexOf(file)
      this.dialogEdit =true
      this.fileName = file.name
    },
    changeFile(){
      this.fileList[this.fileKey].name = this.fileName
      this.dialogEdit = false
    },
    handleDownload(file) {
      this.postForm.thumbUrl = file.thumb
      this.postForm.imgUrl = file.url
    },
    handleSuccess(file, fileList) {
      this.fileList.push(file.data)
    },
    fetchData() {
      fetchBrand().then(response => {
        this.postForm = response.data
        // just for test
        // this.postForm.title += `   文章 Id:${this.postForm.id}`
        // this.postForm.content_short += `   Article Id:${this.postForm.id}`
        if (response.data.images) {
          this.fileList = response.data.images
        }
        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = '编辑'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      this.status = 'publish'
      this.postForm.images = this.fileList
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          createBrand(this.postForm).then(response => {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
